package pl.umk.mat.fred.unicore.urc.storagemanagement.listeners;

import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.IStructuredSelection;

import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.BelowStorageNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.CatalogNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.GridNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.MultiplyCatalogNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.Node;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.StorageNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.views.StorageBrowserView;

public class MenuListener implements IMenuListener {

	private StorageBrowserView view;
	
	public MenuListener(StorageBrowserView view) {
		this.view = view;
	}
	
	@Override
	public void menuAboutToShow(IMenuManager manager) {
		IStructuredSelection selection = (IStructuredSelection)view.getTreeViewer().getSelection();
		boolean areStoragesVisible = false;
		if (!selection.isEmpty()) {
			areStoragesVisible = ((Node) selection.getFirstElement()).getRootNode().areStoragesVisible();
		}
		manager.add(view.getHideShowStoragesAction());
		manager.add(new Separator());
		if ((selection.size() == 1) && (selection.getFirstElement() instanceof BelowStorageNode)) {
			manager.add(view.getRenameAction());
		}
		if (selection.size() > 0) {
			boolean valid = true;
			for (Object o : selection.toList()) {
				if (!(o instanceof BelowStorageNode)) {
					valid = false;
					break;
				}
			}
			if (valid) {
				manager.add(view.getDeleteAction());
				manager.add(view.getChangePermissionsAction());
			}
		}
		if ((selection.size() == 1) && (
				(selection.getFirstElement() instanceof StorageNode) 
				|| (selection.getFirstElement() instanceof CatalogNode)
				|| (selection.getFirstElement() instanceof MultiplyCatalogNode)
				|| (!areStoragesVisible && selection.getFirstElement() instanceof GridNode))) {
			manager.add(view.getCreateNewCatalogAction());
			manager.add(view.getCreateNewFileAction());
			manager.add(view.getSendLocalFileAction());
			manager.add(view.getPasteAction());
			manager.add(view.getFindAction());
			if (view.getClipboard() == null) {
				view.getPasteAction().setEnabled(false);
			} else {
				view.getPasteAction().setEnabled(true);
			}
		}
		if (selection.size() > 0) {
			boolean valid = true;
			for (Object o : selection.toList()) {
				if (!((o instanceof BelowStorageNode) || (o instanceof StorageNode))) {
					valid = false;
					break;
				}
			}
			if (valid) {
				manager.add(view.getdDownloadRemoteFilesAction());
				manager.add(view.getCopyAction());
			}
		}
	}
}
